package bangbang.upanddown;

import bangbang.config.AliyunOssProperties;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class DownloadFiles {
        @Autowired
        AliyunOssProperties aliyunOssProperties;
        public  void downloadFile(String objectName ,String filePath, String bucketName){
            String endpoint=aliyunOssProperties.getEndpoint();
            String accessKeyId =aliyunOssProperties.getAccessKeyId();
            String accessKeySecret =aliyunOssProperties.getAccessKeySecret();

            OSSClient  ossClient= new OSSClient(endpoint, accessKeyId, accessKeySecret);
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            BufferedInputStream in=null;
            try {
                // 读取文件内容。
                System.out.println("Object content:");
                in=new BufferedInputStream(ossObject.getObjectContent());
                byte[] buffer = new byte[1024];
                OutputStream out =new FileOutputStream("C:\\Users\\1\\Desktop\\OssTestFiles\\4.jpg");// response.getOutputStream();
                int len = 0;
                int i=0;
                while ((len = in.read(buffer)) > 0) {
                    i=i+len;
                    ((FileOutputStream) out).write(buffer, 0, len);
                }
                System.out.println(i);
                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
                in.close();
                out.close();
                // 关闭OSSClient。
                ossClient.shutdown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


}
